package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.mongo.VisitorApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;

@Service
public class VisitorApiImpl implements VisitorApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public List<Visitors> queryVisitors(Long userId, int num) {
//        db.getCollection('visitor').find({userId:1}).limit(4).sort({date:-1})
        Query query = new Query(Criteria.where("userId").is(userId));
        query.limit(num);
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        return mongoTemplate.find(query,Visitors.class);

    }

    @Override
    public List<Visitors> queryVisitors(Long userId, Long time, int num) {
        Query query = new Query(Criteria.where("userId").is(userId).and("date").gt(time));
        query.limit(num);
        query.with(Sort.by(Sort.Direction.DESC,"date"));
        return mongoTemplate.find(query,Visitors.class);
    }


    @Override
    public void saveVisitors(Long userId, Long visitorId){
        Visitors visitors = new Visitors();
        visitors.setId(new ObjectId());
        visitors.setVisitorUserId(visitorId);
        visitors.setUserId(userId);
        visitors.setFrom("首页");
        visitors.setDate(new Date().getTime());
        mongoTemplate.save(visitors);
    }
}
